package com.follow.common;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

public class ReaderExcel {


    public List<List<String>> reader(String path) throws Exception{

        Workbook workbook = null;
        InputStream inputStream = new FileInputStream(path);
        if (path.endsWith(".xls")){
            workbook = new HSSFWorkbook(inputStream);
        }else if (path.endsWith("xlsx")){
            workbook = new XSSFWorkbook(inputStream);
        }else {
            return  null;
        }

        return readerData(workbook);

    }

    private List<List<String>> readerData(Workbook workbook){
        Sheet sheet = workbook.getSheetAt(0);//获取sheet表格
        List<List<String>> lists = new ArrayList<>();//存储数据
        for (int i = 1; i < sheet.getPhysicalNumberOfRows(); i++) {//getPhysicalNumberOfRows一共有多少行数据
            List<String> list = new ArrayList<>();
            Row row = sheet.getRow(i);
            for (int j = 0; j < row.getLastCellNum(); j++) {//getLastCellNum最后一列数据

                Cell cell = row.getCell(j);
                String value = "";
                if (cell != null){
                    value = cell.toString();
                }
                list.add(value);
            }
            lists.add(list);
        }
        return  lists;
    }
}
